<?php
/**
 * User:于小涛
 * Date:2020/2/18
 * Time:16:31
 */
namespace app\admin\business\file;
use app\admin\model\file\File as FileModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class File{

    private $obj_file_model=null;
    public function __construct()
    {
        $this->obj_file_model = new FileModel();
    }

    /**
     * 上传文件
     * User:于小涛
     * Date:2020/2/23
     * Time:16:20
     * @param $str_file_key
     * @param string $str_file_new_name
     * @return array
     */
    public function uploadVideoImage($str_file_key,$str_file_new_name=''){
        trace('上传图片','info');
        $file = request()->file($str_file_key);
        $str_savename = \think\facade\Filesystem::putFile( 'Video/vod', $file, function(){return date("Y").'/'.date("m").'/'.date("d").'/'.time().rand(10000000,100000000);});
        $str_savename=str_replace("\\",'/',$str_savename);
        $arr_file_info=pathinfo($file->getOriginalName());
        $arr_file_type=explode('/',$file->getMime());
        $arr_add_data=array(
            'name'=>$str_file_new_name,
            'original_name'=>$arr_file_info['filename'],
            'type'=>$arr_file_type[0],
            'format'=>$arr_file_type[1],
            'url'=>$str_savename,
        );
        $int_num=$this->obj_file_model->add($arr_add_data);
        if($int_num){
            $int_id=$this->obj_file_model->getLastInsID();
            trace('上传成功,数据id：'.$int_id,'info');
            return ['ret'=>0,'reason'=>'success','data'=>['id'=>$int_id,'url'=>$str_savename,'original_name'=>$arr_add_data['original_name']]];
        }else{
            trace('上传失败,加入数据：'.var_export($arr_add_data,true),'error');
            return ['ret'=>1,'reason'=>'上传失败'];
        }
    }

    /**
     * 下载文件
     * User:于小涛
     * Date:2020/2/26
     * Time:16:46
     */
    public function downloadImage($str_img_url){
        $arr_file_info=pathinfo($str_img_url);
        $str_img_content=file_get_contents($str_img_url);
        if(empty($str_img_content)){
            return ['ret'=>1,'reason'=>'下载失败'];
        }
        $str_short_path=rand(1,9);
        $str_file_path=config("filesystem.disks.public.root").'/'.$str_short_path;
        if(!is_dir($str_file_path)){
            mkdir($str_file_path,0777,true);
        }
        $str_file_new_name=rand(100000000000,900000000000);
        $str_new_file=$str_file_path.'/'.$str_file_new_name.'.'.$arr_file_info['extension'];
        file_put_contents($str_new_file,$str_img_content);
        $arr_add_data=array(
            'name'=>$str_file_new_name,
            'original_name'=>$arr_file_info['filename'],
            'type'=>'image',
            'format'=>$arr_file_info['extension'],
            'url'=>$str_short_path.'/'.$str_file_new_name.'.'.$arr_file_info['extension'],
        );
        $int_num=$this->obj_file_model->add($arr_add_data);
        if($int_num){
            $arr_add_data['id']=$this->obj_file_model->getLastInsID();
            return ['ret'=>0,'reason'=>'success','data'=>$arr_add_data];
        }else{
            return ['ret'=>1,'reason'=>'保存失败'];
        }
    }

    /**
     * 获取文件url地址
     * User:于小涛
     * Date:2020/2/26
     * Time:17:02
     * @param $arr_list
     * @param $str_file_key 数组中的图片id的字段，多个使用逗号分隔
     * @param string $str_key_after_str
     * @param string $str_domain
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getFileFullUrlByList(&$arr_list,$str_file_key,$str_key_after_str='_id,_url',$str_domain=''){
        $str_domain=empty($str_domain)?config("app.domain"):$str_domain;
        $str_before_url=config('filesystem.disks.public.url').'/';
        $arr_file_key = explode(',',$str_file_key);
        $arr_file_ids=[];
        foreach($arr_list as $arr_item){
            if(is_array($arr_item)&&array_key_exists($str_file_key,$arr_item)){
                $arr_file_ids[]=$arr_item[$str_file_key];
            }
        }
        $arr_file_list=[];
        $arr_file_data=$this->obj_file_model->whereIn('id',$arr_file_ids)->select()->toArray();
        if(!empty($arr_file_data)){
            $arr_file_list=array_item_key_to_self_key($arr_file_data,'id');
        }
        $arr_key_after_str=explode(',',$str_key_after_str);
        foreach($arr_list as &$arr_item){
            foreach($arr_file_key as $str_key_item){
                if(count($arr_key_after_str)==2){
                    $str_key_after_str=str_replace($arr_key_after_str[0],$arr_key_after_str[1],$str_key_item);
                }else{
                    $str_key_after_str=$str_key_item.$str_key_after_str;
                }
                if(!empty($arr_item[$str_key_item])&&array_key_exists($arr_item[$str_key_item],$arr_file_list)){
                    $arr_item[$str_key_after_str]=$str_domain.$str_before_url.$arr_file_list[$arr_item[$str_file_key]]['url'];
                }else{
                    $arr_item[$str_key_after_str]='';
                }
            }
        }
    }

    public function getFileFullUrlById($int_file_id){
        $arr_info = $this->obj_file_model->findOrEmpty($int_file_id)->toArray();
        $str_domain=empty($str_domain)?config("app.domain"):$str_domain;
        if(!empty($arr_info)){
            $arr_info['full_url'] = $str_domain.config('filesystem.disks.public.url').'/'.$arr_info['url'];
        }
        return $arr_info;
    }

}